import React, { useRef, useEffect, CSSProperties } from "react";
import * as echarts from "echarts";
import type { ECharts, EChartsOption } from "echarts";

// 定义基础图表数据接口
interface BaseChartData {
  series: echarts.SeriesOption[];
}

// 定义坐标轴图表数据接口
interface AxisChartData extends BaseChartData {
  xData: string[];
}

// 定义组件 Props 类型
interface ChartProps {
  style?: CSSProperties;
  chartData: AxisChartData | BaseChartData;
  isAxisChart?: boolean;
}

const Charts: React.FC<ChartProps> = (props) => {
  const { style, chartData, isAxisChart = true } = props;

  // 使用泛型指定 ref 类型
  const echartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<ECharts | null>(null);

  // 坐标轴图表配置
  const axisOption: EChartsOption = {
    textStyle: { color: "#333" },
    tooltip: { trigger: "axis" },
    xAxis: {
      type: "category",
      data: [],
      axisLine: { lineStyle: { color: "#17b3a3" } },
      axisLabel: { interval: 0, color: "#333" },
    },
    yAxis: [
      {
        type: "value",
        axisLine: { lineStyle: { color: "#17b3a3" } },
      },
    ],
    color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
    series: [],
  };

  // 普通图表配置
  const normalOption: EChartsOption = {
    tooltip: { trigger: "item" },
    color: [
      "#0f78f4",
      "#dd536b",
      "#9462e5",
      "#a6a6a6",
      "#e1bb22",
      "#39c362",
      "#3ed1cf",
    ],
    series: [],
  };

  useEffect(() => {
    if (!echartRef.current) return;

    // 初始化图表实例
    chartInstance.current = echarts.init(echartRef.current);

    // 生成最终配置
    let options: EChartsOption;
    if (isAxisChart) {
      const axisData = chartData as AxisChartData;
      options = {
        ...axisOption,
        xAxis: { ...axisOption.xAxis, data: axisData.xData },
        series: axisData.series,
      };
    } else {
      options = {
        ...normalOption,
        series: chartData.series,
      };
    }

    // 设置配置项
    chartInstance.current.setOption(options);

    // 清理函数
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, [chartData, isAxisChart]);

  return <div style={style} ref={echartRef} />;
};

export default Charts;
